#####################################################################
#
# WEB APP FOR RFID READER SDK
# AUTHOR: zengkai001@qq.com
# DATE: 2025-01-24
#
#####################################################################

import sys
import time
import os
from pathlib import Path
from flask import Flask, render_template, request, redirect, flash, jsonify

# Add PYTHON_SDK to path
from route.rfid_reader import RFIDReader

# Global reader instance
reader = None

app = Flask(__name__)

# 动态获取 templates 和 static 目录的路径
app.template_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app.static_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')



app.secret_key = 'dev'  # Required for flash messages

@app.route('/')
def rfid():
    return render_template('rfid.html')

@app.route('/open-device', methods=['POST'])
def open_device():
    global reader
    try:
        if reader is not None:
            return {
                'error': True,
                'message': "Device is already open"
            }
        
        # Get the directory of the current script
        current_dir = os.path.dirname(os.path.abspath(__file__))
        
        # Construct the relative path to the library
        lib_path = os.path.join(current_dir, 'route', 'x86_64', 'libGZAE_rfid.so')
        
        reader = RFIDReader(lib_path)  # Use the constructed relative path
        
        # Open connection (using default connection string)
        reader.open_device("RDType=RL8000;CommType=USB;AddrMode=0;SerNum=")
        
        return {
            'error': False,
            'message': "Device opened successfully"
        }
    except Exception as e:
        return {
            'error': True,
            'message': f"Error opening device: {str(e)}"
        }

@app.route('/device-info', methods=['POST'])
def device_info():
    global reader
    try:
        if reader is None:
            return {
                'error': True,
                'message': "Device not opened. Please open device first."
            }
        
        # Get device info
        info = reader.get_device_info()
        return {
            'error': False,
            'message': f"Device Info: {info}"
        }
    except Exception as e:
        return {
            'error': True,
            'message': f"Error getting device info: {str(e)}"
        }

@app.route('/close-device', methods=['POST'])
def close_device():
    global reader
    try:
        if reader is None:
            return {
                'error': True,
                'message': "Device is not open"
            }
            
        reader.close_device()
        reader = None
        return {
            'error': False,
            'message': "Device closed successfully"
        }
    except Exception as e:
        return {
            'error': True,
            'message': f"Error closing device: {str(e)}"
        }

@app.route('/get-tags-info', methods=['POST'])
def get_tags_info():
    global reader
    try:
        if reader is None:
            return {
                'error': True,
                'message': "Device not opened. Please open device first."
            }
        
        # Start inventory and wait for results
        reader.start_inventory()
        time.sleep(1)  # Wait for inventory to complete
        
        # Get tag info
        tags = reader.get_tag_info()
        return {
            'error': False,
            'tags': tags
        }
    except Exception as e:
        return {
            'error': True,
            'message': f"Error getting tag info: {str(e)}"
        }

@app.route('/read-tag', methods=['POST'])
def read_tag():
    global reader
    try:
        if reader is None:
            return {
                'error': True,
                'message': "Device not opened. Please open device first."
            }
            
        # Get parameters from request
        data = request.get_json()
        uid = data.get('uid')
        block_start = int(data.get('blockStart', 0))
        block_count = int(data.get('blockCount', 1))
        
        if not uid:
            return {
                'error': True,
                'message': "UID is required"
            }
            
        # Read tag data and convert bytes to hex string
        tag_data = reader.read_tag(uid, block_start, block_count)
        if tag_data is None:
            return {
                'error': True,
                'message': "Failed to read tag data"
            }
            
        # Convert bytes to hex string for JSON serialization
        tag_data_hex = tag_data.hex()
        return {
            'error': False,
            'data': tag_data_hex
        }
    except Exception as e:
        return {
            'error': True,
            'message': f"Error reading tag data: {str(e)}"
        }

@app.route('/write-tag', methods=['POST'])
def write_tag():
    global reader
    try:
        if reader is None:
            return {
                'error': True,
                'message': "Device not opened. Please open device first."
            }
            
        # Get parameters from request
        data = request.get_json()
        uid = data.get('uid')
        block_start = int(data.get('blockStart', 0))
        block_count = int(data.get('blockCount', 1))
        tag_data = data.get('tagData')
        
        if not uid:
            return {
                'error': True,
                'message': "UID is required"
            }
        if not tag_data:
            return {
                'error': True,
                'message': "Tag data is required"
            }
            
        # Write to tag
        result = reader.write_tag(uid, block_start, block_count, tag_data)
        if result is None:
            return {
                'error': True,
                'message': "Failed to write tag data"
            }
            
        return {
            'error': False,
            'message': "Tag data written successfully"
        }
    except Exception as e:
        return {
            'error': True,
            'message': f"Error writing tag data: {str(e)}"
        }

@app.route('/enable-eas', methods=['POST'])
def enable_eas():
    global reader
    try:
        if reader is None:
            return {
                'error': True,
                'message': "Device not opened. Please open device first."
            }
            
        # Get UID from request
        data = request.get_json()
        uid = data.get('uid')
        
        if not uid:
            return {
                'error': True,
                'message': "UID is required"
            }
            
        # Enable EAS
        result = reader.enable_eas(uid)
        if result is None:
            return {
                'error': True,
                'message': "Failed to enable EAS"
            }
            
        return {
            'error': False,
            'message': "EAS enabled successfully"
        }
    except Exception as e:
        return {
            'error': True,
            'message': f"Error enabling EAS: {str(e)}"
        }

@app.route('/disable-eas', methods=['POST'])
def disable_eas():
    global reader
    try:
        if reader is None:
            return {
                'error': True,
                'message': "Device not opened. Please open device first."
            }
            
        # Get UID from request
        data = request.get_json()
        uid = data.get('uid')
        
        if not uid:
            return {
                'error': True,
                'message': "UID is required"
            }
            
        # Disable EAS
        result = reader.disable_eas(uid)
        if result is None:
            return {
                'error': True,
                'message': "Failed to disable EAS"
            }
            
        return {
            'error': False,
            'message': "EAS disabled successfully"
        }
    except Exception as e:
        return {
            'error': True,
            'message': f"Error disabling EAS: {str(e)}"
        }

@app.route('/check-eas', methods=['POST'])
def check_eas():
    global reader
    try:
        if reader is None:
            return {
                'error': True,
                'message': "Device not opened. Please open device first."
            }
            
        # Get UID from request
        data = request.get_json()
        uid = data.get('uid')
        
        if not uid:
            return {
                'error': True,
                'message': "UID is required"
            }
            
        # Check EAS status
        status = reader.check_eas(uid)
        if status is None:
            return {
                'error': True,
                'message': "Failed to check EAS status"
            }
            
        return {
            'error': False,
            'status': status,
            'message': "EAS checked successfully"
        }
    except Exception as e:
        return {
            'error': True,
            'message': f"Error checking EAS status: {str(e)}"
        }

@app.route('/write-afi', methods=['POST'])
def write_afi():
    global reader
    try:
        if reader is None:
            return {
                'error': True,
                'message': "Device not opened. Please open device first."
            }
            
        # Get parameters from request
        data = request.get_json()
        uid = data.get('uid')
        afi = data.get('afi')
        
        if not uid:
            return {
                'error': True,
                'message': "UID is required"
            }
        if afi is None:
            return {
                'error': True,
                'message': "AFI value is required"
            }
            
        # Write AFI to tag
        result = reader.write_afi(uid, afi)
        if result is None:
            return {
                'error': True,
                'message': "Failed to write AFI"
            }
            
        return {
            'error': False,
            'message': "AFI written successfully"
        }
    except Exception as e:
        return {
            'error': True,
            'message': f"Error writing AFI: {str(e)}"
        }

@app.route('/get-tag-status', methods=['POST'])
def get_tag_status():
    global reader
    try:
        if reader is None:
            return {
                'error': True,
                'message': "Device not opened. Please open device first."
            }
            
        # Get UID from request
        data = request.get_json()
        uid = data.get('uid')
        
        if not uid:
            return {
                'error': True,
                'message': "UID is required"
            }
            
        # Get tag status
        status = reader.get_tag_status(uid)
        print(status)
        if status is None:
            return {
                'error': True,
                'message': "Failed to get tag status"
            }
            
        return {
            'error': False,
            'status': status,
            'message': "Tag status retrieved successfully"
        }
    except Exception as e:
        return {
            'error': True,
            'message': f"Error getting tag status: {str(e)}"
        }

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
